import React from 'react'
import { Switch, Route } from "react-router-dom";
import configuration from "./routerConfiguration.js"

/**
 * 递归生成路由
 * @param {Array} routerList 
 * @param {String} baseUrl 
 */
function getRouter(routerList, baseUrl) {
  if (!Array.isArray(routerList)) {
    return null;
  }

  const routers = routerList.map((route, i) => {
    const { path, component: Component, children, ...rest } = route;
    let url = baseUrl === '/' ? `/${path}` : `${baseUrl}/${path}`;
    const newPath = url.replace(/\/+/g, '/'); // 保证不会出现重复 //
    return (
      <Route
        key={i}
        path={newPath}
        {...rest}
        exact={!children}
        render={(props) => (
          <Component {...props} >
            {getRouter(children, newPath)}
          </Component>
        )}
      />
    );
  });

  return routers
}

/**
 * 根据配置项，生成路由
 * @returns {JSX.Element}
 */
function ReactRouter() {
  return (
    <Switch>
      {getRouter(configuration.routes, '/')}
    </Switch>
  )
}

export default ReactRouter
